{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Demo Code `（From ChatGPT）`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Demo Code\n",
    "\n",
    "import cv2\n",
    "\n",
    "# 初始化摄像头并获取第一帧\n",
    "video_capture = cv2.VideoCapture(0)\n",
    "_, frame = video_capture.read()\n",
    "frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n",
    "background = frame_gray\n",
    "\n",
    "# 定义阈值参数和结构元素\n",
    "delta_thresh = 20\n",
    "blur_size = 3\n",
    "element_size = 3\n",
    "\n",
    "# 开始循环处理每一帧\n",
    "while True:\n",
    "    # 将当前帧转换为灰度图像，并计算与背景的差异\n",
    "    ret, frame = video_capture.read()\n",
    "    if not ret:\n",
    "        break\n",
    "    \n",
    "    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n",
    "    delta_frame = cv2.absdiff(background, frame_gray)\n",
    "    \n",
    "    # 对差异进行二值化处理，并使用形态学操作来得到图像中的白色区域\n",
    "    _, threshold = cv2.threshold(delta_frame, delta_thresh, 255, cv2.THRESH_BINARY)\n",
    "    blur_kernel = (blur_size, blur_size)\n",
    "    threshold_blur = cv2.blur(threshold, blur_kernel)\n",
    "    element_kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (element_size, element_size))\n",
    "    threshold_blur = cv2.erode(threshold_blur, element_kernel)\n",
    "    threshold_blur = cv2.dilate(threshold_blur, element_kernel)\n",
    "\n",
    "    # 找到轮廓并在原始图像上绘制边界框\n",
    "    contours, _ = cv2.findContours(threshold_blur, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n",
    "    for contour in contours:\n",
    "        (x, y, w, h) = cv2.boundingRect(contour)\n",
    "        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n",
    "\n",
    "    # 显示处理结果\n",
    "    cv2.imshow('frame', frame)\n",
    "\n",
    "    # 如果按下键盘上的 \"q\" 键，则退出循环\n",
    "    if cv2.waitKey(1) > 0:\n",
    "        break\n",
    "\n",
    "# 清理并退出\n",
    "video_capture.release()\n",
    "cv2.destroyAllWindows()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
